package cn.wolfcode;

import cn.wolfcode.config.WebSocketServer;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_RESULT_TOPIC,
        consumerGroup = "MQOrderResultListener"
)
public class MQOrderResultListener implements RocketMQListener<OrderMQResult> {


    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("进入了web socket");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        ConcurrentHashMap<String, WebSocketServer> clients = WebSocketServer.clients;
        WebSocketServer webSocketServer = clients.get(orderMQResult.getToken());
        if (webSocketServer != null) {
            Session session = webSocketServer.getSession();
            RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
            log.info("成功发送了结果数据");
            try {
                basicRemote.sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
